#include "glew/glew.h"

#include "RenderTexture.hpp"

namespace fge
{

RenderTexture::RenderTexture(int width, int height)
{
	this->width = width;
	this->height = height;

	glGenFramebuffersEXT(1, &frameBufferObject);
	glGenTextures(1, &textureId);

	glBindTexture(GL_TEXTURE_2D, textureId);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferObject);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	//GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
}

RenderTexture::~RenderTexture()
{
	glDeleteFramebuffersEXT(1, &frameBufferObject);
}

void RenderTexture::Bind()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferObject);

	glPushAttrib(GL_VIEWPORT_BIT);
	glViewport(0, 0, width, height);

	glClearColor(1, 0, 1, 1);
	glClear(GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();

	glLoadIdentity();
	glOrtho(0, width, height, 0, 1, -1);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glScalef(1, -1, 1);
	glTranslatef(0, -(GLfloat)height, 0);
}

void RenderTexture::Unbind()
{
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glPopAttrib();

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

}
